<?php
namespace app\admin\controller;

use think\facade\Session;
use think\facade\Request;
use app\common\util\Upload as Up;
use app\common\model\AdminPhoto as P;

class Ueditor extends Base{
	private $timg='img_record';
	private $tfile='file_record';
	
	/*
	 *	空间文件上传方法
	 */
	public function upload(){
		$action=I('get.action');
		$conf=array();
		switch($action){
			case 'file':														//上传文件
				$up_path='file/'.date('Ymd');
				$upload=init_file_upload($up_path,$conf);						//实例化上传对象
				if($upload->upload()){
					$up_info=$upload->getUploadFileInfo();
					$url='/'.$up_info[0]['savepath'].$up_info[0]['savename'];
					$result=array('error' => 0,'url' => $url);
					$result=array_merge($result,$up_info[0]);
					$this->fileRrecord($up_info);
				}else{
					$result=array('error' => 1,'message' => $upload->getErrorMsg());
				}
				
				echo json_encode($result);
				die;
			default:															//默认上传图片
				/*
				 *	生成缩略图方法： U('Ueditor/upload',array('thumb'=>'200X200')
				 */
				$thumb=I('get.thumb');
				$up_path='system';
				if($thumb!=''){
					$thumb=explode(',',$thumb);				//切割多图
					foreach($thumb as $v){
						$t=explode('X',$v);					//切割宽高
						$conf['thumbMaxWidth']=$t[0].',';
						$conf['thumbMaxHeight']=$t[0].',';
					}
					$conf['thumb']=true;
					$conf['thumbMaxWidth']=substr($conf['thumbMaxWidth'],0,-1); 
					$conf['thumbMaxHeight']=substr($conf['thumbMaxHeight'],0,-1); 
				}else{
					$conf['thumb']=false;
				}
				$upload=init_img_upload($up_path,$conf);					//实例化上传对象

				if($upload->upload()){
					$up_info=$upload->getUploadFileInfo();
					if($conf['thumb']==true){
						$up_info[0]['thumbName']=env('upload.thumb_prefix').$up_info[0]['savename'];
						$thumb_url='/'.$up_info[0]['savepath'].$up_info[0]['thumbName'];
					}else{
						$thumb_url='';
					}
					$url='/'.$up_info[0]['savepath'].$up_info[0]['savename'];
					
					$this->imgRrecord($up_info);
					$result=array('error' => 0,'url' => $url,'thumb_url'=>$thumb_url);
				}else{
					$result=array('error' => 1,'message' => $upload->getErrorMsg());
				}
				echo json_encode($result);
				die;
		}
	}
	
	/*
	 *	图片空间方法
	 */
	public function managerJson(){
		//根目录路径
		$pic_path=env('upload.up_img_path').'system/';
		$current_path = $_SERVER['DOCUMENT_ROOT'].'/'.$pic_path;
		$current_url = 'http://'.$_SERVER['HTTP_HOST'].'/'.$pic_path;
		$current_dir_path = '';
		$moveup_dir_path = '';
		
		//图片扩展名
		$ext_arr = array('gif', 'jpg', 'jpeg', 'png', 'bmp');

		//排序形式，name or size or type
		$order = empty($_GET['order']) ? 'name' : strtolower($_GET['order']);
		
		//不允许使用..移动到上一级目录
		if (preg_match('/\.\./', $current_path)) {
			echo 'Access is not allowed.';
			exit;
		}
		//最后一个字符不是/
		if (!preg_match('/\/$/', $current_path)) {
			echo 'Parameter is not valid.';
			exit;
		}

		//目录不存在或不是目录
		if (!file_exists($current_path) || !is_dir($current_path)) {
			echo 'Directory does not exist.';
			exit;
		}
		//遍历目录取得文件信息
		$file_list = array();
		if ($handle = opendir($current_path)) {
			$i = 0;
			while (false !== ($filename = readdir($handle))) {
				if ($filename[0] == '.') continue;
				//屏蔽缩略图
				if(strpos($filename,'thumb_') !== false) continue;
				
				$file = $current_path . $filename;
				if (is_dir($file)) {
					$file_list[$i]['is_dir'] = true; //是否文件夹
					$file_list[$i]['has_file'] = (count(scandir($file)) > 2); //文件夹是否包含文件
					$file_list[$i]['filesize'] = 0; //文件大小
					$file_list[$i]['is_photo'] = false; //是否图片
					$file_list[$i]['filetype'] = ''; //文件类别，用扩展名判断
				} else {
					$file_list[$i]['is_dir'] = false;
					$file_list[$i]['has_file'] = false;
					$file_list[$i]['filesize'] = filesize($file);
					$file_list[$i]['dir_path'] = '';
					$file_ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
					$file_list[$i]['is_photo'] = in_array($file_ext, $ext_arr);
					$file_list[$i]['filetype'] = $file_ext;
				}
				$file_list[$i]['filename'] = $filename; //文件名，包含扩展名
				$file_list[$i]['datetime'] = date('Y-m-d H:i:s', filemtime($file)); //文件最后修改时间
				$i++;
			}
			closedir($handle);
		}

		usort($file_list, 'cmp_func');
		
		$result = [];
		//相对于根目录的上一级目录
		$result['moveup_dir_path'] = $moveup_dir_path;
		//相对于根目录的当前目录
		$result['current_dir_path'] = $current_dir_path;
		//当前目录的URL
		$result['current_url'] = $current_url;
		//文件数
		$result['total_count'] = count($file_list);
		//文件列表数组
		$result['file_list'] = $file_list;
		
		echo json_encode($result);
		die;
	}
	
	/*
	 *	编辑器图片上传方法
	 */
	public function imageUp(){
		header("Content-Type: text/html; charset=utf8");

		$info=[
			'state'=>'SUCCESS',
			'url'=>'',
			'original'=>'',
			'title'=>'上传图片',
		];
		$info["title"]='上传图片';
		/*
		 *	如果前台需要调用编辑器的上传方式的话，则修改NUM的获取方式
		 */
		 
		$up_path='editor';											//上传路径
		$result=Up::putFile(Request::file(),$up_path,$this->uuid);
		if($result['code']==200){
			$info['url']=$result['data']['src'];
			$info['original_name']=$result['data']['original_name'];
		}else{
			$info['state']=$result['msg'];
		}
		/*
		 * 向浏览器返回数据json数据
		 * {
		 *   'url'      :'a.jpg',   //保存后的文件路径
		 *   'title'    :'hello',   //文件描述，对图片来说在前端会添加到title属性上
		 *   'original' :'b.jpg',   //原始文件名
		 *   'state'    :'SUCCESS'  //上传状态，成功时返回SUCCESS,其他任何值将原样返回至图片上传框中
		 * }
		 */
		return json($info);
	}
	
	/*
	 *	编辑器图片管理
	 */
	public function imageManager(){
		$photo_list = P::getAll(['uuid'=>$this->uuid]);
		$photo_list=$photo_list['data'];
		$data=[
			'state' => 'SUCCESS',
			'start' => 0,
			'total' => count($photo_list),
			'list' =>[],
		];
		foreach($photo_list as $v){
			$data['list'][]=[
				'mtime'=>strtotime($v['create_time']),
				'url'=>$v['href'],
			];
		}
		return json($data);
	}
	
	/*
	 *	远程抓图方法
	 */
	public function getRemoteImage(){
		header("Content-Type: text/html; charset=gbk");
		error_reporting(E_ERROR|E_WARNING);
		//远程抓取图片配置
		$path=C('UP_IMG_PATH').'editor/';
		$config = array(
			"savePath" => $path,        												//保存路径
			"allowFiles" => array( ".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp" ) , //文件允许格式
			"maxSize" => 3000                    //文件大小限制，单位KB
		);
		$uri = htmlspecialchars( $_POST[ 'upfile' ] );
		$uri = str_replace( "&amp;" , "&" , $uri );
		$this->getRemoteImage_sub( $uri,$config );		
	}
	
	/*
	 *	记录图片上传
	 */
	public function imgRrecord($result,$source=1){
		foreach($result as $v){
			$path='/'.$v['savepath'];
			if(isset($v['thumbName']) && $v['thumbName']!=''){
				$thumb=$path.$v['thumbName'];
			}else{
				$thumb='';
			}
			$data=array(
				'extension'=>$v['extension'],
				'http_path'=>'http://'.$_SERVER['HTTP_HOST'].$path.$v['savename'],
				'img_path'=>$path.$v['savename'],
				'base_path'=>$v['name'],
				'thumb'=>$thumb,
				'size'=>$v['size'],
				'source'=>$source,
				'addtime'=>time(),
			);
			Db::name($this->timg)->insert($data);
		}
	}
	
	/*
	 * 记录文件上传
	 */
	public function fileRrecord($result,$source=1){
		foreach($result as $v){
			$path='/'.$v['savepath'];
			$data=array(
				'extension'=>$v['extension'],
				'type'=>$v['type'],
				'http_path'=>'http://'.$_SERVER['HTTP_HOST'].$path.$v['savename'],
				'file_path'=>$path.$v['savename'],
				'base_path'=>$v['name'],
				'hash'=>md5(time().rand(1000,9999)),
				'size'=>$v['size'],
				'source'=>$source,
				'addtime'=>time(),
			);
			Db::name($this->tfile)->insert($data);
		}
	}
	
	//远程抓取图片保存本地
	public function getRemoteImage_sub( $uri,$config){
		//忽略抓取时间限制
		set_time_limit( 0 );
		//ue_separate_ue  ue用于传递数据分割符号
		$imgUrls = explode( "ue_separate_ue" , $uri );
		$tmpNames = array();
		foreach ( $imgUrls as $imgUrl ) {
			//http开头验证
			if(strpos($imgUrl,"http")!==0){
				array_push( $tmpNames , "error" );
				continue;
			}
			//获取请求头
			$heads = get_headers( $imgUrl );
			//死链检测
			if ( !( stristr( $heads[ 0 ] , "200" ) && stristr( $heads[ 0 ] , "OK" ) ) ) {
				array_push( $tmpNames , "error" );
				continue;
			}
	
			//格式验证(扩展名验证和Content-Type验证)
			$fileType = strtolower( strrchr( $imgUrl , '.' ) );
			if ( !in_array( $fileType , $config[ 'allowFiles' ] ) || stristr( $heads[ 'Content-Type' ] , "image" ) ) {
				array_push( $tmpNames , "error" );
				continue;
			}
	
			//打开输出缓冲区并获取远程图片
			ob_start();
			$context = stream_context_create(
				array (
					'http' => array (
						'follow_location' => false // don't follow redirects
					)
				)
			);
			//请确保php.ini中的fopen wrappers已经激活
			readfile( $imgUrl,false,$context);
			$img = ob_get_contents();
			ob_end_clean();
	
			//大小验证
			$uriSize = strlen( $img ); //得到图片大小
			$allowSize = 1024 * $config[ 'maxSize' ];
			if ( $uriSize > $allowSize ) {
				array_push( $tmpNames , "error" );
				continue;
			}
			//创建保存位置
			$savePath = $config[ 'savePath' ];
			if ( !file_exists( $savePath ) ) {
				mkdir( "$savePath" , 0777 );
			}
			//写入文件
			$file_name = rand( 1 , 10000 ) . time() . strrchr( $imgUrl , '.' );
			$tmpName = $savePath . $file_name;
			try {
				$fp2 = @fopen( $tmpName , "a" );
				fwrite( $fp2 , $img );
				fclose( $fp2 );
				array_push( $tmpNames ,  $file_name );
			} catch ( Exception $e ) {
				array_push( $tmpNames , "error" );
			}
			
			$data=array(
				array(
					'extension'=>str_replace('.','',$fileType),
					'savename'=>$tmpName,
					'size'=>$uriSize,
					'name'=>$uri,
				),
			);
			$this->imgRrecord($data,2);					// 2为远程抓取
		}
		/**
		 * 返回数据格式
		 * {
		 *   'url'   : '新地址一ue_separate_ue新地址二ue_separate_ue新地址三',
		 *   'srcUrl': '原始地址一ue_separate_ue原始地址二ue_separate_ue原始地址三'，
		 *   'tip'   : '状态提示'
		 * }
		 */
		echo "{'url':'" . implode( "ue_separate_ue" , $tmpNames ) . "','tip':'远程图片抓取成功！','srcUrl':'" . $uri . "'}";
		die();
	}
}
?>